#include <camera.hpp>
#include <JHCap2/JHCap.h>
#include <opencv2/opencv.hpp>
#include <unistd.h>
#include <time.h>


using namespace cv;
using namespace std;

Camera::Camera() {
    
    while(CameraInit(device_id) != API_OK) {
        sleep(1);
    }
    CameraSetGain(device_id, GAIN);
    CameraSetExposure(device_id, exposure);
    width = 720; 
    height = 480;
    len = 0;
    CameraSetResolution(device_id, 0, &width, &height);
    CameraGetResolution(device_id, 0, &width, &height);
    CameraGetImageBufferSize(device_id, &len, CAMERA_IMAGE_BMP);
    CameraSetSnapMode(device_id, CAMERA_SNAP_CONTINUATION);
}

Camera::~Camera() {
    CameraFree(0);
}

bool Camera::getImage(Mat &src) {

    
    src = Mat(height, width, CV_8UC3);
    // printf("%d %d", width, height)
    if(CameraQueryImage(0, (unsigned char*)src.data, &len, CAMERA_IMAGE_BMP)==API_OK) {
        // struct timespec *t;
        // t = (struct timespec *) malloc(sizeof(t));
        // clock_gettime(CLOCK_MONOTONIC, t);
        // printf("%ld\n", t->tv_nsec);
        // free(t)
        return true;
    }else {
        usleep(100);
        return false;
    }
}

bool Camera::setFrameRate(int frame_per_second) {
    //unit: ms
    int delay = 1000 / frame_per_second;
    if(CameraSetDelay(device_id, delay) == API_OK) {
        return true;
    }
    return false;
}